﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using nRoute.Components;
using nRoute.Mapping;
using nRoute.ViewModels;
using Windows.ApplicationModel.Core;
using Windows.UI.Xaml;

namespace SimpleShell.ViewModels
{
    [MapViewModel(typeof(MainPage))]
    public class MainPageViewModel : ViewModelBase
    {
        private IDisposable _token;

        public MainPageViewModel()
        {
            SetupCommands();
        }

        public string MemoryUsage
        {
            get { return string.Format("{0} KB", (GC.GetTotalMemory(false) / 1024).ToString("###,###")); }
        }

        public ActionCommand GCCommand { get; set; }

        public ActionCommand StartMemCommand { get; set; }

        public ActionCommand StopMemCommand { get; set; }

        private void SetupCommands()
        {
            this.GCCommand = new ActionCommand(GC.Collect);

            this.StartMemCommand = new ActionCommand(() =>
            {
                if (_token != null) return;
                _token = Observable.Interval(TimeSpan.FromSeconds(1)).ObserveOnDispatcher().Subscribe((l) =>
                {
                    base.NotifyPropertyChanged(() => MemoryUsage);
                });

                this.StopMemCommand.RequeryCanExecute();
            },
            () => _token == null);

            this.StopMemCommand = new ActionCommand(() =>
            {
                if (_token != null) _token.Dispose();
                _token = null;

                this.StartMemCommand.RequeryCanExecute();
            }, 
            () => _token != null);
        }
    }
}
